/**
 * Copyright (C) 2007 Mustafa K. Isik - isik@acm.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

package com.paxcodi.rmi.fibonacci.server;

import java.math.BigInteger;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class FibonacciImplementation extends UnicastRemoteObject implements
	Fibonacci {
    
    private static final long serialVersionUID = 8022851158448409L;

    public FibonacciImplementation() throws RemoteException{
	
	super();	//creates a UniCastRemoteObject on some port and starts it listening for connections	
    }
    
        public BigInteger getFibonacci(final int n) throws RemoteException {
            
	return this.getFibonacci(new BigInteger(Long.toString(n)));
    }

    public BigInteger getFibonacci(final BigInteger n) throws RemoteException {
	
	System.out.println("Calculating the " + (n.intValue() + 1) + "th Fibonacci number");
	final BigInteger zero = new BigInteger("0");
	final BigInteger one = new BigInteger("1");
	
	if(n.equals(zero) || n.equals(one)) return one;
	
	BigInteger i = one; 	//indicates ith Fibonacci number, i.e. i = 3 is synonymous to the third Fibonacci number
	BigInteger low = one; 	//pre-precursor
	BigInteger high = one;	//precursor
	
	BigInteger temp;
	while(i.compareTo(n) == -1){ //while (i < n)
	    temp = high;
	    high = high.add(low);
	    low = temp;
	    i = i.add(one);	    
	}
	
	return high;
    }

}
